package com.itcast.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itcast.constant.RedisConstant;
import com.itcast.entity.PageResult;
import com.itcast.entity.QueryPageBean;
import com.itcast.mapper.CheckGroupMapper;
import com.itcast.mapper.CheckItemMapper;
import com.itcast.mapper.SetmealMapper;
import com.itcast.pojo.CheckGroup;
import com.itcast.pojo.CheckItem;
import com.itcast.pojo.Setmeal;
import com.itcast.service.SetmealService;
import com.itcast.utils.QiniuUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;

    //新增检查套餐
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //插入数据
        setmealMapper.add(setmeal);
        //获取主键
        Integer setmealId = setmeal.getId();
        //循环数组
        for (Integer checkgroupId : checkgroupIds) {
            //添加套餐和检查组的关系表
            setmealMapper.addSetmealCheckGroup(setmealId,checkgroupId);
        }
        String fileName = setmeal.getImg();
        //将img文件名存入到redis中
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);

        //当添加套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }

    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml(){
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setmealMapper.findAll();

        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        //需要生成套餐详细静态页面
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表件套页面
    public void generateMobileSetmealListHtml(List<Setmeal> list){
        Map map = new HashMap();
        //为模板提供数据，用于生成静态页面
        map.put("setmealList",list);
        generteHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //生成套餐详细静态页面(可能有两个)
    public void generateMobileSetmealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",this.findByIdSetMeal(setmeal.getId()));

            generteHtml("setmeal_detail.ftl","setmeal_detail_"+setmeal.getId()+".html",map);
        }
    }

    //通用方法，用于生成静态页面
    public void generteHtml(String templateName, String htmlPageName, Map map){
        //获取配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //解决输出时乱码问题
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outPutPath+"/"+htmlPageName),"utf-8"));
            //构造输出流
            //out = new FileWriter(new File(outPutPath+"/"+htmlPageName));

            //输出文件
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //查询总数
        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setmealMapper.findPage(queryString);
        long total = page.getTotal();
        List<Setmeal> rows = page.getResult();
        return new PageResult(total,rows);
    }

    //删除检查套餐
    @Override
    public void deleteById(Integer id) {
        //根据id删除多表关系
        setmealMapper.deleteSetmealGroup(id);
        //根据id查询t_setmeal数据获取image
        Setmeal setmeal = setmealMapper.findById(id);
        //删除七牛云服务器的图片
        String img = setmeal.getImg();
        //System.out.println(img);
        if (img!=null){
            QiniuUtils.deleteFileFromQiniu(img);
        }
        //根据id删除t_setmeal数据
        setmealMapper.deleteById(id);
    }

    //查询所有用于展示
    @Override
    public List<Setmeal> findAll() {

        return setmealMapper.findAll();
    }

    @Autowired
    private CheckGroupMapper checkGroupMapper;
    @Autowired
    private CheckItemMapper checkItemMapper;

    //查询单个套餐对象
    @Override
    public Setmeal findByIdSetMeal(int id) {
        //根据id查询单个套餐对象
        Setmeal setmeal = setmealMapper.findById(id);

        //根据id查询t_checkgroup表的有关套餐的检查组数据
        List<CheckGroup> checkGroupList = checkGroupMapper.findSetmealIdByGroup(id);

        //循环遍历checkGroupList得到id
        for (CheckGroup checkGroup : checkGroupList) {
            //根据checkGroupID查询检查项的数据
            List<CheckItem> checkItemList = checkItemMapper.findCheckGroupIdByItem(checkGroup.getId());
            checkGroup.setCheckItems(checkItemList);
        }
        setmeal.setCheckGroups(checkGroupList);

        return setmeal;
    }

    //扇形统计图数据展示
    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealMapper.findSetmealCount();
    }
}
